import 'dart:ui' as ui;

import 'package:flutter_kit_dsp/flutter_kit_dsp.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import 'lang/my_i19n.dart';
import 'modules/my_home.dart';
import 'modules/my_home_controller.dart';
import 'tool/assets.dart';

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
ui.Image? _thumbImage;

Future<void> _loadThumbImage() async {
  // final ByteData data = await rootBundle.load(assets.thumb); // 读取图片资源
  // final List<int> bytes = data.buffer.asUint8List();
  // final image = await decodeImageFromList(Uint8List.fromList(bytes));
  // _thumbImage = image;
}

Future<void> main() async {
  /// 捕获所有未捕获的 Dart 异常
  LogManager.initFireBase(
    crashTest: false,
    runMain: () async {
      I19n.init();
      requestPermission();
      initRealm();
      registerDelegate();
      // _loadThumbImage();
      BluetoothManager.key = navigatorKey;

      // SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight])
      SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]).then((_) {
        GetxManager.initGetx();
        runApp(const MyApp());
      });
    },
  );
}

void registerDelegate() {
  CHDefaultConfig().lineColors = [0xFFEA3019];
  CHDefaultConfig().inNumbers = 1;
  CHDefaultConfig().ch_sample.db = 60;
  CHDefaultConfig().ch_sample.max_db = 100;
  CHDefaultConfig().ch_sample.min_db = 0;
  CHDefaultConfig().signList = [20, 40, 60, 80, 100, 120, 150, 180];
  CHDefaultConfig().axisY_label = [20, 40, 60, 80, 100, 120, 150, 180];
  CHDefaultConfig().sign_sample.Q = 1.41;
  CHDefaultConfig().sign_sample.min_Q = 0.2;
  CHDefaultConfig().sign_sample.max_Q = 10;
  CHDefaultConfig().sign_sample.gain = 0;
  CHDefaultConfig().sign_sample.min_gain = -12;
  CHDefaultConfig().sign_sample.max_gain = 12;
  CHDefaultConfig().sign_sample.freq = 20;
  CHDefaultConfig().sign_sample.min_freq = 20;
  CHDefaultConfig().sign_sample.max_freq = 200;

  CHDefaultConfig().low_pass_sample.freq = 200;
  CHDefaultConfig().low_pass_sample.min_freq = 40;
  CHDefaultConfig().low_pass_sample.max_freq = 200;
  CHDefaultConfig().low_pass_sample.type = CHDefaultConfig().passTypes[1];
  CHDefaultConfig().high_pass_sample.freq = 20;
  CHDefaultConfig().high_pass_sample.min_freq = 20;
  CHDefaultConfig().high_pass_sample.max_freq = 200;
  for (var e in CHDefaultConfig().passTypes) {
    e.slopeList.clear();
    e.slopeList.addAll([6, 12, 18, 24]);
  }
  Get.lazyPut(() => MyHomeController());

  DelegateRegistry.register<HomePageDelegate>(() => MyHome());
}

void initRealm() {
  // // 创建不同模型的 RealmManager 实例
  RealmManager.schemaVersion = 2;
  RealmManager<GlobalModel>(
    allSchemas: [
      SignModel.schema,
      PassType.schema,
      Passmodel.schema,
      ChannelModel.schema,
      VolumeModel.schema,
      REMModel.schema,
      GlobalModel.schema,
    ],
  );
  // 创建不同模型的 RealmManager 实例
}

Future<void> requestPermission() async {
  BluetoothManager.instance.requestPermissions();
  await Permission.microphone.request();
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    // 隐藏状态栏
    /// SystemUiMode.immersiveSticky：隐藏状态栏和导航栏，用户可以从屏幕边缘滑动重新显示。
    /// SystemUiMode.immersive：隐藏状态栏和导航栏，但不会自动重新显示。
    /// SystemUiMode.leanBack：隐藏状态栏和导航栏，但更容易重新显示。
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
    SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        statusBarColor: Colors.black, // 状态栏背景色
        statusBarIconBrightness: Brightness.light, // 状态栏图标颜色 (白色图标)
      ),
    );
    return GetMaterialApp(
      navigatorKey: navigatorKey,
      locale: const Locale('zh'),
      localizationsDelegates: Flutter_Kit_Share_Localizations.localizationsDelegates,
      supportedLocales: Flutter_Kit_Share_Localizations.supportedLocales,
      title: 'DSP BT AUDIO',
      debugShowCheckedModeBanner: false,
      initialRoute: AppPages.INITIAL,
      getPages: AppPages.routes,
      color: Color_bg_btn,
      theme: ThemeData(
        // 设置全局 AppBar 主题
        appBarTheme: const AppBarTheme(
          centerTitle: true,
          backgroundColor: Colors.transparent, // AppBar 背景颜色
          elevation: 0,
          titleTextStyle: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), // AppBar 标题文本颜色
        ),

        // 设置全局文本颜色
        textTheme: const TextTheme(
          bodySmall: TextStyle(color: Colors.black), // 小号文本颜色
          bodyMedium: TextStyle(color: Colors.black), // 中号文本颜色
          bodyLarge: TextStyle(color: Colors.black), // 大号文本颜色
        ),

        ///全局slider设置
        sliderTheme: SliderThemeData(
          trackHeight: 7,
          activeTrackColor: Color_theme, // 滑动过的颜色
          inactiveTrackColor: Color_inTrackColor, // 未滑动部分的颜色
          // activeTrackColor: Colors.transparent, // 滑动过的颜色
          // inactiveTrackColor: Colors.transparent, // 未滑动部分的颜色
          thumbColor: Color_theme, // 滑块的颜色
          overlayColor: Colors.red.withOpacity(0.2), // 滑块按下时的颜色
          activeTickMarkColor: Colors.transparent, // 隐藏刻度线
          inactiveTickMarkColor: Colors.transparent, // 隐藏刻度线
          thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 10.0), // 自定义滑块的形状和大小
          overlayShape: const RoundSliderOverlayShape(overlayRadius: 0.0), // 设置圆点到两端的间距为 0 以减小间距
          trackShape: null,
          tickMarkShape: RoundSliderTickMarkShape(tickMarkRadius: 0), //不显示刻度
          // thumbShape: CustomSliderThumbShape(_thumbImage),
          // thumbIcon: Image.asset('assets/slider_thumb.png'), // 自定义滑点图片
        ),

        switchTheme: SwitchThemeData(
          // trackColor: WidgetStatePropertyAll(Color(0xFF00A1D5)),
          trackColor: WidgetStateProperty.resolveWith((states) {
            if (states.contains(WidgetState.selected)) {
              return Color_theme; // 打开状态的背景颜色
            }
            return Color_disEnable; // 关闭状态的背景颜色
          }),
          trackOutlineColor: const WidgetStatePropertyAll(Colors.black),
          trackOutlineWidth: const WidgetStatePropertyAll(1),
          overlayColor: const WidgetStatePropertyAll(Colors.transparent),
          thumbColor: const WidgetStatePropertyAll(Color_thumbColor),
        ),

        highlightColor: Color_theme, // 按钮等组件点击时的高亮颜色
        splashColor: Colors.white.withAlpha(100), // 点击时的水波纹颜色
        colorScheme: ColorScheme.fromSeed(seedColor: Color_theme),

        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.transparent, // 背景色
            foregroundColor: Colors.white, // 文字 & 图标颜色
            shadowColor: Colors.transparent, // 阴影颜色（透明表示无阴影）
            overlayColor: Color_theme,
            elevation: 0, // 阴影高度
            textStyle: const TextStyle(
              // 字体样式
              fontSize: 14,
              fontWeight: FontWeight.normal,
            ),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.zero), // 按钮形状
            padding: EdgeInsets.symmetric(horizontal: 5, vertical: 0),
            alignment: Alignment.centerLeft,
          ),
        ),
        useMaterial3: true,
      ),
      builder: (context, child) {
        return MediaQuery(
          //限制字体不会因系统字体放大而影响
          data: MediaQuery.of(context).copyWith(textScaler: const TextScaler.linear(1.0)),
          child: EasyLoading.init()(context, child),
        );
      },
    );
  }
}
